using System;
using System.Web;
using System.Web.UI;

namespace nToolbox.Web
{
    public static class WebHelper
    {

        /// <summary>
        /// Takes a relative path and returns the absolute path (including any sub folders)
        /// </summary>        
        /// <remarks>
        /// How do you unit test HTTPContext properly?
        /// </remarks>
        public static string FixUrl(string Url)
        {
            string strReturn = Url;
            if (Url.StartsWith("~"))
            {
                strReturn = Url.Substring(1);
                if (HttpContext.Current.Request.ApplicationPath != "/")
                {
                    strReturn = HttpContext.Current.Request.ApplicationPath + strReturn.Replace("//", "/");
                }
            }
            return strReturn;
        }

        /// <summary>
        /// Checks to see if the string passed starts with http:// or https://
        /// </summary>        
        /// <remarks>
        /// This could be changed to use the RFC standard for URLs/URIs (http://www.w3.org/Addressing/)
        /// </remarks>
        public static bool IsValidUrl(string strUrl)
        {
            return (StringHelper.Left(strUrl, 7) == "http://") || (StringHelper.Left(strUrl, 8) == "https://");            
        }

        /// <summary>
        /// Finds the control that caused the postback
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        /// <remarks>
        /// Taken from http://ryanfarley.com/blog/archive/2005/03/11/1886.aspx
        /// </remarks>
        public static Control GetPostBackControl(Page page)
        {
            Control control = null;

            string ctrlname = page.Request.Params.Get("__EVENTTARGET");
            if (ctrlname != null && ctrlname != string.Empty)
            {
                control = page.FindControl(ctrlname);
            }
            else
            {
                foreach (string ctl in page.Request.Form)
                {
                    Control c = page.FindControl(ctl);
                    if (c is System.Web.UI.WebControls.Button)
                    {
                        control = c;
                        break;
                    }
                }
            }
            return control;
        }
    }
}
